package com.crb.crm.manage.web.biz.excel;

import com.crb.crm.manage.enums.ExcelType;
import com.crb.crm.manage.enums.OssType;
import com.crb.crm.manage.dao.biz.UploadRecordMapper;
import com.crb.crm.manage.entity.biz.UploadRecordSearchDTO;
import com.crb.crm.manage.excel.ExcelTemplate;
import com.crb.crm.manage.oos.OSSUtilCtx;
import com.crb.crm.manage.pojo.biz.UploadRecord;
import com.crb.crm.manage.service.biz.UploadRecordService;
import com.crb.crm.manage.utils.PageDataResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 上传记录
 *
 * @author huangjian
 */
@Controller
@RequestMapping("/uploadRecord")
public class UploadRecordController {

    private static final Logger logger = LoggerFactory
            .getLogger(UploadRecordController.class);
    @Autowired
    private UploadRecordService service;
    @Autowired
    private UploadRecordMapper mapper;
    @Autowired
    private OSSUtilCtx ossUtilCtx;

    @RequestMapping("/uploadRecordList")
    public String toMessageSendRecordList(ModelMap map) {
        List<?> models = Arrays.stream(ExcelTemplate.values()).map(ExcelTemplate::getDesc).collect(Collectors.toList());
        map.addAttribute("models", models);

        List<OssType> ossTypes = Arrays.stream(OssType.values()).collect(Collectors.toList());
        map.addAttribute("ossTypes", ossTypes);
        return "biz/excel/uploadRecordList";
    }

    /**
     * 分页查询文件上传记录列表
     *
     * @return ok/fail
     */
    @RequestMapping(value = "/getUploadRecords", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions(value = "getUploadRecords")
    public PageDataResult getUploadRecords(@RequestParam("page") Integer page,
                                           @RequestParam("limit") Integer limit, UploadRecordSearchDTO search) {
        logger.debug("分页查询文件上传记录列表！搜索条件：search：" + search + ",page:" + page
                + ",每页记录数量limit:" + limit);
        PageDataResult pdr = new PageDataResult();
        try {
            if (null == page) {
                page = 1;
            }
            if (null == limit) {
                limit = 10;
            }
            // 获取文件上传记录
            pdr = service.getUploadRecords(search, page, limit);
            logger.debug("文件上传记录列表查询=pdr:" + pdr);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("文件上传记录列表查询异常！", e);
        }
        return pdr;
    }


    /**
     * 文件记录excel表格下载
     */
    @RequestMapping(value = "/downLoadUploadRecordFile", method = RequestMethod.GET)
    @RequiresPermissions(value = {"uploadRecordErrorDown", "uploadRecordSrcDown"})
    @ResponseBody
    public void downLoadUploadRecordFile(HttpServletResponse response, Integer id, String type) throws Exception {
        logger.debug("文件记录excel表格下载！条件：id：" + id + ",type:" + type);
        ExcelType excelType = ExcelType.valueOf(type);
        if (Objects.nonNull(excelType) && id != null) {
            UploadRecord uploadRecord = mapper.selectByPrimaryKey(id);
            InputStream inputStream;
            String fileName;
            String key;
            if (!Objects.isNull(uploadRecord)) {
                String ossTypeCode = uploadRecord.getOssType();
                OssType ossType = OssType.valueOf(ossTypeCode);
                switch (excelType) {
                    case ERROR:
                        fileName = URLEncoder.encode(uploadRecord.getErrFileId(), "UTF-8");
                        key = excelType.getFoder().concat("/").concat(uploadRecord.getErrFileId());
                        if(ossType==OssType.OSS_QINIU){
                            key = uploadRecord.getErrFileId();
                        }
                        break;
                    case ORIGINAL:
                        //原始文件
                        fileName = URLEncoder.encode(uploadRecord.getSrcFileId(), "UTF-8");
                        key = excelType.getFoder().concat("/").concat(uploadRecord.getSrcFileId());
                        if(ossType==OssType.OSS_QINIU){
                            key = uploadRecord.getSrcFileId();
                        }
                        break;
                    default:
                        throw new IllegalArgumentException("参数错误，请您稍后再试");
                }
                inputStream = ossUtilCtx.download(ossType,key);
                if (!Objects.isNull(inputStream)) {
                    // 配置文件下载
                    response.setHeader("content-type", "application/octet-stream");
                    response.setContentType("application/octet-stream");
                    // 下载文件能正常显示中文
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                    // 实现文件下载
                    byte[] buffer = new byte[1024];
                    BufferedInputStream bis = null;
                    try {
                        bis = new BufferedInputStream(inputStream);
                        OutputStream os = response.getOutputStream();
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                        }
                        System.out.println("Download  successfully!");
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("Download  failed!");
                    } finally {
                        if (bis != null) {
                            try {
                                bis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (inputStream != null) {
                            try {
                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    System.out.println("文件不存在，请您稍后再试");
                }
            }else{
                System.out.println("Download  failed,文件找不到");
            }
        } else {
            System.out.println("参数错误，请您稍后再试");
        }
    }

    /**
     * 错误记录excel表格下载
     */
    @RequestMapping(value = "/checkErrorUploadFile", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> checkErrorUploadFile(Integer id) {
        UploadRecord uploadRecordWithBLOBs = mapper.selectByPrimaryKey(id);
        Map<String, Object> map = new HashMap<>();
        if (!Objects.isNull(uploadRecordWithBLOBs)
                && Objects.nonNull(uploadRecordWithBLOBs.getErrFileId())) {
            map.put("msg", "ok");
        } else {
            map.put("msg", "错误记录不存在，请您稍后再试");
        }
        return map;
    }
}
